﻿using JTActiveSafety.Gateway.Abstractions;
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace JTActiveSafety.Gateway.InMemoryMQ
{
    public class JTActiveSafetyMsgConsumer : IJTActiveSafetyMsgConsumer
    {
        private JTActiveSafetyMsgChannel _channel;
 
        public JTActiveSafetyMsgConsumer(JTActiveSafetyMsgChannel channel)
        {
            _channel = channel;
        }

        public CancellationTokenSource Cts { get; } = new CancellationTokenSource();

        public string TopicName { get; } = "JTActiveSafetyPackage";

        public void Dispose()
        {

        }

        public void OnMessage(Action<(string SIM, byte[] Data)> callback)
        {
            Task.Run(async() => 
            {
                //while (!Cts.IsCancellationRequested)
                //{
                //    var reader = await Channel.Channel.Reader.ReadAsync(Cts.Token);
                //    callback(reader);
                //}
                while (await _channel.Output.WaitToReadAsync(Cts.Token))
                {
                    while (_channel.Output.TryRead(out var mes))
                    {
                        callback(mes);
                    }
                }

            }, Cts.Token);
        }

        public void Subscribe()
        {
            
        }

        public void Unsubscribe()
        {
            Cts.Cancel();
        }
    }
}
